<template>
  <van-address-edit
    :area-list="areaList"
    show-delete
    show-set-default
    show-search-result
    :address-info="AddressInfo"
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    @save="OnSave"
    @delete="OnDelete"
  />
</template>

<script setup>
// 引入地区数据
import { areaList } from "@vant/area-data";
// 代理对象
const { proxy } = getCurrentInstance();
// 获取用户数据
const business = proxy.$business;
// 响应式数据
const AddrId = ref(proxy.$route.query.addrid ?? 0); // 接收地址栏参数
const AddressInfo = ref({});
// 挂载前钩子
onBeforeMount(() => {
  GetAddressInfo();
});
const GetAddressInfo = async () => {
  // 组装参数
  let params = {
    busid: business.value.id,
    addrid: AddrId.value,
  };
  // 发起请求
  let result = await proxy.$http.post({
    url: "/address/info",
    params,
  });
  // 根据请求结果处理
  if (result.code === 1) {
    let info = result.data;
    // 回显数据
    AddressInfo.value = {
      name: info.consignee,
      tel: info.mobile,
      areaCode: info.district
        ? info.district
        : info.city
        ? info.city
        : info.province,
      addressDetail: info.address,
      isDefault: info.status == 1 ? true : false,
    };
  } else {
    proxy.$fail({
      message: result.msg,
      onClose: () => {
        proxy.$router.back();
      },
    });
  }
};
// 保存
const OnSave = async (values) => {
  // 组装参数
  let params = {
    id: AddrId.value,
    busid: business.value.id,
    consignee: values.name,
    mobile: values.tel,
    code: values.areaCode,
    address: values.addressDetail,
    status: values.isDefault === true ? 1 : 0,
  };
  // 发起请求
  let result = await proxy.$http.post({
    url: "/address/edit",
    params,
  });
  // 处理请求结果
  if (result.code === 1) {
    proxy.$success({
      message: result.msg,
      onClose: () => {
        proxy.$router.back();
      },
    });
  } else {
    proxy.$fail(result.msg);
  }
};
// 删除
const OnDelete = () => {
  proxy
    .$confirm({
      title: "删除地址",
      message: "是否确认删除该地址",
    })
    .then(async () => {
      // 组装参数
      let params = {
        busid: business.value.id,
        addrid: AddrId.value,
      };
      // 发起请求
      let result = await proxy.$http.post({
        url: "/address/del",
        params,
      });
      // 处理请求结果
      if (result.code === 1) {
        proxy.$success({
          message: result.msg,
          onClose: () => {
            proxy.$router.back();
          },
        });
      } else {
        proxy.$fail(result.msg);
      }
    });
};
</script>